package com.kafka.core;

import java.util.Iterator;
import java.util.Properties;

import kafka.message.MessageAndMetadata;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.ibatis.session.SqlSession;

import com.kafka.bean.Message;
import com.kafka.dao.IMessageOperation;
import com.kafka.util.BaseUtil;
import com.kafka.util.DbUtil;

public class BaseClass {
	SqlSession sqlSession = DbUtil.getSessionFactory().openSession(true);
	IMessageOperation messageDao = sqlSession
			.getMapper(IMessageOperation.class);
	public static String encode;
//	public static String appID;
//	public static String secretKey;
	public final static Integer success = 1;
	public final static Integer fail = 0;

	static {
		try {
			Properties properties = new Properties();
			properties.load(BaseClass.class.getClassLoader().getResourceAsStream(
					"sysconfig.properties"));
			encode = properties.getProperty("encode");
//			appID = properties.getProperty("AppID");
//			secretKey = properties.getProperty("SecretKey");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void addMessage(MessageAndMetadata<String, String> mam,
			Integer status, String description) {
		Message msg = new Message();
		msg.setTopic(mam.topic());
		msg.setMessage(mam.message());
		JSONObject json = JSONObject.fromObject(mam.message());
		msg.setMessageType(json.getString("msgtype"));
		msg.setCreateTime(json.getString("createtime"));
		msg.setTime(BaseUtil.getDate());
		msg.setStatus(status);
		msg.setDescription(description);
		messageDao.insertMessageInfo(msg);
		sqlSession.commit();
	}
	
	/**
	 * 重构json
	 * @param json
	 * @return
	 */
	protected JSONObject rebuildJSON(JSONObject json){
		JSONObject rJson = new JSONObject();
		Iterator<?> it = json.keys();
        while (it.hasNext()) {  
            String key = (String) it.next();  
            String value = json.getString(key); 
            rJson.put(BaseUtil.strToLower(key), value);
        }
        return rJson;
	}
	
	/**
	 * 重构jsonArray
	 * @param jsonArray
	 * @return
	 */
	protected JSONArray rebuildJSONArray(JSONArray jsonArray){
		JSONArray rJsonArray = new JSONArray();
		for (int i = 0; i < jsonArray.size(); i++) {
			JSONObject obj = JSONObject.fromObject(jsonArray.get(i));
			rJsonArray.add(rebuildJSON(obj));
		}
		return rJsonArray;
	}
}
